// src/stores/orderStore.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useOrderStore = defineStore('order', () => {
  const orders = ref([])
  const loading = ref(false)
  const error = ref(null)

  const fetchAllOrders = async () => {
    try {
      loading.value = true
      const response = await axios.get('/api/order/getAllOrder')
      if (response.data.status === 0) {
        orders.value = response.data.data
      }
    } catch (err) {
      error.value = err.response?.data?.message || '获取订单失败'
    } finally {
      loading.value = false
    }
  }

  const fetchUserOrders = async (userId) => {
    try {
      loading.value = true
      const response = await axios.get('/api/order/getOrder', { params: { userId } })
      if (response.data.status === 0) {
        return response.data.data
      }
    } catch (err) {
      error.value = err.response?.data?.message || '获取用户订单失败'
    } finally {
      loading.value = false
    }
  }

  const addOrder = async (orderData) => {
    try {
      loading.value = true
      const response = await axios.post('/api/order/addOrder', orderData)
      if (response.data.status === 0) {
        await fetchAllOrders()
        return true
      }
    } catch (err) {
      error.value = err.response?.data?.message || '创建订单失败'
      return false
    } finally {
      loading.value = false
    }
  }

  const deleteOrder = async (orderNum) => {
    try {
      loading.value = true
      const response = await axios.post('/api/order/delOrder', { orderNum })
      if (response.data.status === 0) {
        await fetchAllOrders()
        return true
      }
    } catch (err) {
      error.value = err.response?.data?.message || '删除订单失败'
      return false
    } finally {
      loading.value = false
    }
  }

  return {
    orders,
    loading,
    error,
    fetchAllOrders,
    fetchUserOrders,
    addOrder,
    deleteOrder
  }
})